package com.sky.youxue.service;

import com.sky.youxue.common.utils.Md5Utils;
import com.sky.youxue.mapper.UserMapper;
import com.sky.youxue.user.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;



    /**
     * 用户注册的方法
     * @param user
     * @param code
     * @return
     */
    public Boolean register(User user, String code) {
        //判断用户的数据类型是否正确
        String username = user.getUsername();
        String password = user.getPassword();
        String phone = user.getPhone();
//        String regex = "^[0-9a-zA-Z_]{1,26}$";
//        if (!username.matches(regex)||!password.matches(regex)) {
//            return false;
//        }
//        //判断验证码是否正确
//        String redisCode = this.redisTemplate.opsForValue().get(KEY_PREFIX + phone);
//        if (redisCode==null&&code==null&&!redisCode.equals(code)){
//            return false;
//        }
        //对密码进行加密
        String salt = Md5Utils.generate();
        String md5Password = Md5Utils.encryptPassword(password, salt);
        user.setSalt(salt);
        user.setPassword(md5Password);
        Date createTime = new Date(System.currentTimeMillis());
        user.setCreated(createTime);
        //向数据库中添加数据
        Boolean result = false;
        result = this.userMapper.insertSelective(user)==1;
        //注册成功，将redis中的验证码删除
//        if (result) {
//            try {
//                this.redisTemplate.delete(KEY_PREFIX + phone);
//            } catch (Exception e) {
//                logger.error("删除redis中的数据失败，key：{}"+KEY_PREFIX + phone);
//            }
//        }
        return result;
    }

    public User queryUserByIdAndPassword(String username, String password) {
        User record = new User();
        record.setUsername(username);
        User user = this.userMapper.selectOne(record);
        if (user==null){
            return null;
        }
        String passwordSql = user.getPassword();
        String salt = user.getSalt();
        String md5Password = Md5Utils.encryptPassword(password, salt);
        if (md5Password==null||md5Password==null||!md5Password.equals(passwordSql)){
            return null;
        }
        return user;
    }

    public Boolean updateUser(User user){
        int count = userMapper.updateByPrimaryKeySelective(user);
        return count==1;
    }

    public Boolean deleteUser(User user){
        int count = userMapper.deleteByPrimaryKey(user);
        return count==1;
    }
}
